//
//  YQSMSCodeVC.m
//  KingRetail
//
//  Created by yuqin on 2019/7/15.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQSMSCodeVC.h"
#import "YQCodeView.h"
#import "YQRegisterVC.h"

@interface YQSMSCodeVC ()

@property (nonatomic, strong) YQCodeView *codeView;
//@property (nonatomic, strong) NSTimer *timers;

@end

@implementation YQSMSCodeVC
{
    NSInteger _second;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.headView.image = YQ_IMAGE(@"");
    self.headView.backgroundColor = WhiteColor;
    [self.iconAndTitleLeftBtn setImage:YQ_IMAGE(@"back_arrow") forState:UIControlStateNormal];
    _second = 59;
    [self.view addSubview:self.codeView];
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headView.mas_bottom).offset(0);
        make.right.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

- (YQCodeView *)codeView {
    if (!_codeView) {
        _codeView = [[YQCodeView alloc] init];
        _codeView.backgroundColor = WhiteColor;
        NSArray *titleArr = @[@"登录",@"下一步"];
        [_codeView.loginBtn setTitle:titleArr[[self.isRegister integerValue]-1] forState:UIControlStateNormal];
        NSString *teleStr = [self.teleNum stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        _codeView.teleNumLab.text = [NSString stringWithFormat:@"短信验证码已发送至 +86 %@",teleStr];
        //倒计时
        [self cutDownTime];
        WeakSelf(self);
        _codeView.SendCodeBlock = ^{
            //请求数据
            NSDictionary *parameters = @{@"phoneNum":weakSelf.teleNum,
                                         @"countryCode":@"86"
                                         };
            [LCProgressHUD showLoading:@"发送中..."];
            [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"users2/loginOrRegisterMsg") appendParameters:nil bodyParameters:parameters successBlock:^(id responseObject) {
                BaseModel *base = [BaseModel modelWithJson:responseObject];
                
                if (base.code == 0) {
                    [LCProgressHUD showSuccess:@"发送成功"];
                    [weakSelf cutDownTime];
                }else {
                    [LCProgressHUD hide];
                }
            } failureBlock:^(NSError *error) {
                
            }];
        };
        
        
        
        _codeView.LoginOrRegisterBlock = ^{
            
            if ([weakSelf.isRegister integerValue] == 1) {
                //判断验证码是否填写
                if (isEmptyString(weakSelf.codeView.codeTF.text)) {
                    [LCProgressHUD showMessage:@"请填写验证码"];
                    return ;
                }
                NSDictionary *parameters = @{@"validateKey":weakSelf.validateKey,
                                             @"messageCode":weakSelf.codeView.codeTF.text
                                             };
                [LCProgressHUD showLoading:@"登录中..."];
                //登录
                [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"users2/validateLoginOrRegisterMsg") appendParameters:nil bodyParameters:parameters successBlock:^(id responseObject) {
                    BaseModel * base = [BaseModel modelWithJson:responseObject];
                    if (base.code == 0) {
                        [LCProgressHUD hide];
                        UserInfo * userInfo = [UserInfo sharedUserInfo];
                        [userInfo mj_setKeyValues:base.data];
                        [UserInfo sharedUserInfo].bIsLogin = YES;
                        //记录token
                        //记录账号、密码
                        [kDefaults setObject:[responseObject[@"data"] objectForKey:@"token"] forKey:@"token"];
                        [kDefaults synchronize];
                        
                        NSLog(@"===== %@",[kDefaults objectForKey:@"token"]);
                        
                        [LCProgressHUD showSuccess:@"登录成功"];
                        //跳转首页
                        TheAppDel.window.rootViewController =[TabBarController singletonTabBarController];
                    }else {
                        [LCProgressHUD hide];
                        [UserInfo sharedUserInfo].bIsLogin = NO;
                        [LCProgressHUD showFailure:responseObject[@"msg"]];
                    }
                } failureBlock:^(NSError *error) {
                    [UserInfo sharedUserInfo].bIsLogin = NO;
                }];
            }else {
                //注册
                YQRegisterVC *vc = [[YQRegisterVC alloc] init];
                vc.validateKey = self.validateKey;
                YQ_PUSH(vc);
            }
        };
        
    }
    return _codeView;
}

//倒计时
- (void)cutDownTime {
    WeakSelf(self);
    __block NSInteger time = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [weakSelf.codeView.cutDownBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                
                weakSelf.codeView.cutDownBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [weakSelf.codeView.cutDownBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                weakSelf.codeView.cutDownBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

@end
